
(import
  (scheme base)
  (scheme read)
  (scheme write)
  (scheme process-context)
  (scheme load)
  (scheme cxr)
  (only (gauche base) make-keyword)
  (only (gauche base) string-split)
  (makiki))

(include "./web-server.scm")

(define default-port 43334)

(define (main args)
  (define current-port
    (if (null? (cdr args))
        default-port
        (string->number (cadr args))))

  (start-http-server (make-keyword "port") current-port
                     (make-keyword "error-log") #t))

;; front-end handler
(define-http-handler (GET) "/"
  (lambda (req app)
    (respond/ok req (list 'sxml index-page))))

(define-http-handler "/index.html"
  (lambda (req app)
    (respond/ok req (list 'sxml index-page))))

;; scripting handler
(define-http-handler "/draw.js"
  (lambda (req app)
    (respond/ok req '(file "canvas.js"))))

;; new id handler
(define-http-handler (POST) "/api/NewId"
  (lambda (req app)
    (respond/ok req (list 'json (string->number (api-new-id!))))))

;; push buffer handler
(define-http-handler (POST) "/api/PushBuffer"
  (lambda (req app)
    (let ((body (utf8->string (read-request-body req))))
      (respond/ok req (list 'json (api-push-buffer! body))))))

;; push bulk buffer handler
(define-http-handler (POST) "/api/PushBulkBuffer"
  (lambda (req app)
    (let ((body (utf8->string (read-request-body req))))
      (respond/ok req (list 'json (api-push-bulk-buffer! body))))))

;; pull buffer handler
(define-http-handler (POST) "/api/PullBuffer"
  (lambda (req app)
    (let ((body (utf8->string (read-request-body req))))
      (respond/ok req (list 'json (api-pull-buffer! body))))))

;; clear buffer handler
(define-http-handler (POST) "/api/ClearBuffer"
  (lambda (req app)
    (api-clear-buffer!)))

(main (command-line))
